package com.ruoyi.generator.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.generator.entity.*;
import com.ruoyi.generator.mapper.ContractMapper;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("contract")
public class ContractController extends BaseController {

    @Autowired
    private com.ruoyi.generator.service.ContractService ContractService;

    @Autowired
    private com.ruoyi.generator.mapper.ContractMapper ContractMapper;

    @PostMapping("/add")
    public AjaxResult createContract(@RequestBody Contract Contract) {
        return toAjax( ContractService.insertContract(Contract));
    }

    @PostMapping("/addkunbang")
    public AjaxResult addkunbang(@RequestBody Contract[] Contracts) {
        int successCount = 0;
        Long maxId = ContractMapper.getMaxId();
        // 计算下一个ID
        Long nextId = (maxId != null) ? maxId + 1 : 1;

        for (Contract contract : Contracts) {
            contract.setNextId(nextId);
            successCount += ContractService.insertContract(contract);
        }
        return toAjax(successCount);
    }

    @PostMapping("/addReturnValue")
    public int addReturnValue(@RequestBody StReturnValue stReturnValue) {
        stReturnValue.setFormType("add");
        int returnValue =ContractService.addReturnValue(stReturnValue);
        return returnValue;
    }


    @PostMapping("/update")
    public AjaxResult updateContract(@RequestBody Contract Contract) {
        return toAjax( ContractService.updateContractByCode(Contract));
    }

    @GetMapping("/clientlist")
    public List<Map<String, String>> clientlist() {
        // 直接获取客户列表
        List<Customer> customers = ContractService.selectClientlist();

        // 创建一个用于返回的客户数据列表
        List<Map<String, String>> clientList = new ArrayList<>();
        for (Customer customer : customers) {
            Map<String, String> clientData = new HashMap<>();
            clientData.put("id", String.valueOf(customer.getId())); // 假设你的Contract类有getId()方法
            clientData.put("name", customer.getCustomerName()); // 假设你的Contract类有getName()方法
            clientData.put("code", customer.getCustomerCode()); // 假设你的Contract类有getCode()方法

            clientList.add(clientData);
        }

        // 返回客户数据列表
        return clientList;
    }


    /**
     * 导出合同信息列表
     */
    @Log(title = "合同列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContractSearchCriteria ContractSearchCriteria)
    {
        List<Contract> list = ContractService.ContractList(ContractSearchCriteria);
        ExcelUtil<Contract> util = new ExcelUtil<Contract>(Contract.class);
        util.exportExcel(response, list, "合同列表");
    }


    /**
     * 下载模版
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<Contract> util = new ExcelUtil<Contract>(Contract.class);
        util.importTemplateExcel(response, "合同数据");
    }

    /**
     * 导入客户信息
     */
    @Log(title = "合同列表", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Contract> util = new ExcelUtil<Contract>(Contract.class);
        List<Contract> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = ContractService.importCustomer(userList, updateSupport, operName);
        return success(message);
    }



    @GetMapping("/list")
    public TableDataInfo list(ContractSearchCriteria ContractSearchCriteria)
    {
        startPage();
        List<Contract> list = ContractService.selectContractList(ContractSearchCriteria);
        return getDataTable(list);
    }

    /**
     * 处理 GET 请求，接收 contractCode 参数
     */
//    @GetMapping("/getContractByCode")
//    public AjaxResult getContractByCode(@RequestParam String contractCode) {
//        try {
//            // 调用服务层方法获取合同信息
//            Contract contract = ContractService.selectContractByCode(contractCode);
//            Contract contract = ContractService.queryReturnValue(contractCode);;
//            if (contract != null) {
//                return AjaxResult.success(contract);
//            } else {
//                return AjaxResult.error("合同不存在");
//            }
//        } catch (Exception e) {
//            return AjaxResult.error("查询失败：" + e.getMessage());
//        }
//    }

    @GetMapping("/queryMoth")
    public PaymentMsgVO queryMoth(StReturnValue returnValue)
    {
        PaymentMsgVO paymentMsgVO = ContractService.queryMoth(returnValue);
        System.out.println("paymentMsgVO:" + paymentMsgVO);
        return (paymentMsgVO);
    }
    @GetMapping("/queryReturnValue")
    public List<StReturnValue> queryReturnValue(@RequestParam String contractCode)
    {
        StReturnValue returnValue = new StReturnValue();
        returnValue.setContractCode(contractCode);
        List<StReturnValue> list = ContractService.queryReturnValue(returnValue);
        return list;
    }

    @GetMapping("/queryInvoiceList")
    public List<InvoiceForm> queryInvoiceList(@RequestParam String contractCode) {
        System.out.println("queryInvoiceList contractCode:" + contractCode);
        return ContractService.queryInvoiceList(contractCode);

    }

    @GetMapping("/queryContractNumberByLike")
    public List<String> queryContractNumberByLike(@RequestParam String queryString) {
        System.out.println("queryContractNumberByLike queryString:" + queryString);
        return ContractService.queryContractNumberByLike(queryString);

    }


    /**
     * 删除客户信息
     */
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{contractCode}")
    public AjaxResult remove(@PathVariable String  contractCode) throws SchedulerException, TaskException
    {
        ContractService.deleteContractBycontractCode(contractCode);
        return success();
    }

}
